package com.eric.text;

import java.util.ArrayList;
import java.util.List;

import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.library.UserDefineLibrary;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.jsoup.nodes.Document;

import com.eric.Config;
import com.eric.utils.DictionaryUtils;

public class AnsjSegWorker extends AbstractTextWorker {

	private Result r;

	public AnsjSegWorker(Object input) {
		super(input);
	}

	@Override
	public void produce() {
		result = produce(text, doc);
	}

	@Override
	protected void initThis() {
		if (customWords.size() > 0) {
			for (String s : customWords) { // 添加自定义词典
				UserDefineLibrary.insertWord(s);
			}
		}
	}

	@Override
	public List<String> getContext() {
		for (int i = 0; i < r.size(); i++) {
			if (acceptedText(r.get(i).getName())) {
				StringBuilder sb = new StringBuilder();
				if (i > 1 && i < r.size() - 1) {
					if (acceptedText(r.get(i - 1).getName()))
						sb.append(r.get(i - 1).getName() + Config.KW_PAIR_SEPARATOR);

					sb.append(r.get(i).getName());

					if (acceptedText(r.get(i + 1).getName()))
						sb.append(Config.KW_PAIR_SEPARATOR + r.get(i + 1).getName());
				}
				contextWords.add(sb.toString());
			}
		}
		return contextWords;
	}

	@Override
	public List<String> produce(String text, Document doc) {
		List<String> list = new ArrayList<>();
		DictionaryUtils.autoAddKeywordsFromDocument(customWords, doc);// 需要先根据原始DOC把关键词加入
		initThis();

		r = ToAnalysis.parse(text);

		for (Term t : r) {
			if (acceptedText(t.getName())) // 筛选分词后的结果，主要是移除标点符号等
				list.add(t.getName());
		}

		if (removeStopWords)
			removeStopWords(list, stopWords);// 移除停用词

		return list;
	}

}
